const Router = require('koa-router');
const db = require('../db'); // 你已有的数据库封装
const router = new Router({ prefix: '/api/gift' });

// 获取列表（支持状态筛选、分页）
router.get('/list', async (ctx) => {
  const { page = 1, pageSize = 10, status = '' } = ctx.query;
  const offset = (page - 1) * pageSize;
  const whereClause = status && status !== '全部' ? 'WHERE status = ?' : '';
  const params = status && status !== '全部' ? [status] : [];

  const totalSql = `SELECT COUNT(*) as count FROM gift_orders ${whereClause}`;
  const [{ count }] = await db.query(totalSql, params);

  const listSql = `SELECT * FROM gift_orders ${whereClause} ORDER BY created_at DESC LIMIT ?, ?`;
  const listParams = [...params, parseInt(offset), parseInt(pageSize)];
  const list = await db.query(listSql, listParams);

  ctx.body = {
    code: 200,
    data: list[0],
    pagination: {
      total: count,
      current: parseInt(page),
      pageSize: parseInt(pageSize),
    },
  };
});

// 添加礼物订单
router.post('/add', async (ctx) => {
  const {
    order_no,
    title,
    image_url,
    price,
    quantity,
    buyer_name,
    status = '待支付',
  } = ctx.request.body;

  const sql = `INSERT INTO gift_orders (order_no, title, image_url, price, quantity, buyer_name, status)
               VALUES (?, ?, ?, ?, ?, ?, ?)`;

  await db.query(sql, [order_no, title, image_url, price, quantity, buyer_name, status]);

  ctx.body = { code: 200, message: '添加成功' };
});

// 删除礼物订单
router.delete('/delete/:id', async (ctx) => {
  const { id } = ctx.params;
  const sql = `DELETE FROM gift_orders WHERE id = ?`;
  await db.query(sql, [id]);
  ctx.body = { code: 200, message: '删除成功' };
});

// 修改礼物订单
router.put('/update/:id', async (ctx) => {
  const { id } = ctx.params;
  const {
    status,
    title,
    image_url,
    price,
    quantity,
    buyer_name,
    received_count
  } = ctx.request.body;

  const sql = `UPDATE gift_orders SET
                status = ?, title = ?, image_url = ?, price = ?, quantity = ?, buyer_name = ?, received_count = ?
               WHERE id = ?`;

  await db.query(sql, [status, title, image_url, price, quantity, buyer_name, received_count, id]);

  ctx.body = { code: 200, message: '更新成功' };
});

// 根据ID获取单条
router.get('/:id', async (ctx) => {
  const { id } = ctx.params;
  const sql = `SELECT * FROM gift_orders WHERE id = ?`;
  const [row] = await db.query(sql, [id]);
  ctx.body = { code: 200, data: row };
});

module.exports = router;
